import time

import pandas as pd

from 币安涨跌幅监控.config import exchange
from 币安涨跌幅监控.utils.commons import sleep_until_run_time
from 币安涨跌幅监控.utils.dingding import send_dingding_msg

# 涨跌幅阈值
PRICE_CHANGE_INDEX = 0.05


# 获取币安交易所币种的数据
def symbol():
    all_symbol = exchange.fapiPublicGetExchangeInfo()['symbols']
    all_symbol = pd.DataFrame(all_symbol)['symbol']
    all_symbol = all_symbol.to_list()
    return all_symbol


def line(all_symbol):
    up_list = []
    down_list = []
    for i in all_symbol:
        param = {
            'symbol': i,
            'interval': '1d',
            'limit': 2
        }
        data = exchange.fapiPublicGetKlines(params=param)
        data = pd.DataFrame(data)
        data.rename(columns={0: 'MTS', 1: 'open', 2: 'high', 3: 'low', 4: 'close', 5: 'volume'}, inplace=True)
        data['MTS'] = data['MTS'].astype(float)  # str类型，直接使用pd.to_datetime(df['MTS'], unit='ms') 会有精度偏差，故先要转换为int或float
        data['candle_begin_time'] = pd.to_datetime(data['MTS'], unit='ms')
        data = data[['candle_begin_time', 'open', 'high', 'low', 'close', 'volume']]
        # data['change'] = round(data['close'].astype(float) / data['close'].astype(float).shift() - 1, 4)  # 会报SettingWithCopyWarning警告信息
        data['change'] = round(data.loc[:, 'close'].astype(float) / data.loc[:, 'close'].astype(float).shift() - 1, 4)

        if data['change'].iloc[-1] > PRICE_CHANGE_INDEX:  # 涨跌幅设置，此处为涨跌幅大于PRICE_CHANGE_INDEX则返回数据
            up_list.append(i)
        if data['change'].iloc[-1] < -PRICE_CHANGE_INDEX:  # 涨跌幅设置，此处为涨跌幅大于PRICE_CHANGE_INDEX则返回数据
            down_list.append(i)
        time.sleep(0.5)

    return up_list, down_list


if __name__ == '__main__':
    while True:
        try:
            symbol_data = symbol()
            # symbol_data = symbol_data[:10] # debug
            up_data, down_data = line(symbol_data)
            dingding_msg = ''
            if len(up_data) and len(down_data) == 0:
                send_dingding_msg('当前没有符合条件的币种')
            else:
                dingding_msg = f'24h涨幅大于{PRICE_CHANGE_INDEX * 100}% 的币种为：' + str(up_data)
                dingding_msg += f'\n24h跌幅大于{PRICE_CHANGE_INDEX * 100}% 的币种为：' + str(down_data)
                send_dingding_msg(dingding_msg)
            run_time = sleep_until_run_time('6h')
        except Exception as err:
            msg = '系统出错，10s之后重新运行，出错原因: ' + str(err)
            print(msg)
            send_dingding_msg(msg)
            time.sleep(10)
